﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;

namespace QuanLyThuNgan
{
    public partial class frm_RaToaThuoc : DevExpress.XtraEditors.XtraForm
    {
        public frm_RaToaThuoc()
        {
            InitializeComponent();
        }
        DonVi_Khac dv_khac = new DonVi_Khac();
        DataTable dtkhoitao = new DataTable();
        DataTable dtThuoc = new DataTable();
        ThuocNoiTruMstCTL tntmstctl = new ThuocNoiTruMstCTL();
        int machung; public DataTable _dvd = new DataTable();
        public BenhNhanInfo bninfo = new BenhNhanInfo();
        public BenhNhanInfo Bninfo
        {
            get { return bninfo; }
            set { bninfo = value; }
        }
        DataTable dtBS = new DataTable();
        private void frm_RaToaThuoc_Load(object sender, EventArgs e)
        {
            LoadFrom();
            LoadDSPhieu();
        }
        public void DatatableKhoitao()
        {
            DataTable dtkhoitao = new DataTable();
            dtkhoitao.Columns.Add("bdid", typeof(int));
            dtkhoitao.Columns.Add("dvt", typeof(string));
            dtkhoitao.Columns.Add("slg", typeof(int));
            dtkhoitao.Columns.Add("slgcosan", typeof(float));
            dtkhoitao.Columns.Add("dongia", typeof(int));
            dtkhoitao.Columns.Add("giabhyt", typeof(int));
            dtkhoitao.Columns.Add("langay", typeof(int));
            dtkhoitao.Columns.Add("slglan", typeof(int));
            dtkhoitao.Columns.Add("slgsd", typeof(float));
            dtkhoitao.Columns.Add("usageid", typeof(int));//Phuong thuc ;
            dtkhoitao.Columns.Add("dvsudung", typeof(string));
            dtkhoitao.Columns.Add("tgdung", typeof(string));
            dtkhoitao.Columns.Add("buoidung", typeof(string));
            dtkhoitao.Columns.Add("thanhtien", typeof(int));
            dtkhoitao.Columns.Add("sobn", typeof(string));
            gridControl_thuoc.DataSource = dtkhoitao;
        }
        public DataTable m_DataTable(string _ma, string _ten, string giatri_ten1, string giatri_ten2)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn(_ma, typeof(string)));
            dt.Columns.Add(new DataColumn(_ten, typeof(string)));
            DataRow dr = dt.NewRow();
            DataRow dr3 = dt.NewRow();
            dr3[_ma] = "1";
            dr3[_ten] = giatri_ten1;
            dt.Rows.Add(dr3);
            dr[_ma] = "2";
            dr[_ten] = giatri_ten2;
            dt.Rows.Add(dr);

            return dt;
        }
        public void m_gridView_CellValueChanged(GridView _g, DataRow dow, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int currentCol = e.Column.VisibleIndex;
            DataRow dr = _g.GetDataRow(_g.FocusedRowHandle);
            if (currentCol == _g.Columns["bdid"].VisibleIndex)
            {
                string donvitinh = dv_khac.DVTChuyenDoi(dow["dvt"].ToString());
                donvitinh = Uit.it_Font.VNIToUnicode(donvitinh);
                dr["dvt"] = donvitinh;
               // dr["slg"] = 1;
                dr["dongia"] = dow["dongia"];
                dr["giabhyt"] = dow["giabhyt"];
               // dr["slgsd"] = 1;
            }
            if (currentCol == _g.Columns["slgcosan"].VisibleIndex ||currentCol == _g.Columns["slg"].VisibleIndex)
            {
                if ( dr["slg"]!=null)
                {
                    float soluong= float.Parse(dr["slgcosan"].ToString() == "" ? "0" : dr["slgcosan"].ToString()) + float.Parse(dr["slg"].ToString() == "" ? "0" : dr["slg"].ToString());
                    dr["slgsd"] = soluong;
                    if (dr["dongia"] != null)
                       dr["thanhtien"]= soluong * float.Parse(dr["dongia"].ToString());
                }
            }

          
        }
        void  LoadFrom()
        {
            dtBS = dv_khac.DMBacSi();
            ClassHelp.m_SearchLookUpEdit(dtBS, scboBS, "TenBS", "IDBS");
            dtDenNgay.EditValue = Uit.it_Date.CurrentDate2();
            dt_TuNgay.EditValue = Uit.it_Date.CurrentDate2();
            DatatableKhoitao();
            DataTable dtNoi= dv_khac.DonVi_Pharma();
            foreach (DataRow dr in dtNoi.Rows)
            {
                dr["tendv"] = Uit.it_Font.VNIToUnicode(dr["tendv"].ToString());
            }
            DataTable dt_buoidung = m_DataTable("idtgdung", "tgdung", "Trước ăn", "Sau ăn");
            DataSet dsload = dv_khac.Load_All_DanhMuc_ToaThuoc();
            dtThuoc = dsload.Tables[0];
            ClassHelp.m_LookUpEdit(dtNoi, cbo_noigiaothuoc, "tendv", "madv");
            ClassHelp.m_RepositoryItenSearchLookUpEdit(dsload.Tables[0], rpscbo_thuoc, "tenbd", "bdid");
            ClassHelp.m_LoadLookupEditIngridView(dsload.Tables[1], rpcboPhuongThuc, "cachdungthuoc","usageid");
            ClassHelp.m_LoadLookupEditIngridView(dsload.Tables[2], rpcboDonViDung, "dvsudung", "dvsudung");
            ClassHelp.m_LoadLookupEditIngridView(dt_buoidung, rpcboTGDung, "tgdung", "idtgdung");
            ClassHelp.m_LoadLookupEditIngridView(dsload.Tables[3], rpcboBuoiDung, "buoidung", "buoidung");
            _dvd= dv_khac.LayDSDVD();
            txthoten.Text = bninfo.Ten;
            txtGioiTinh.Text = bninfo.Gioi;
            txtsonhapvien.Text = bninfo.SoNhapVien;
            txttuoi.Text = bninfo.Tuoi.ToString();
            txtDiaChi.Text = bninfo.DiaChi;
            txtngaylanh.Text = Uit.it_Date.CurrentDate("dd/MM/yyyy");
            txtthang.Text = Uit.it_Date.CurrentDate("MM-yyyy");
            cbo_noigiaothuoc.EditValue = "K1";
            if (bninfo.Bhytxv && bninfo.Ngaybhyt == "")
                radioGroup1.SelectedIndex = 1;
            else
                radioGroup1.SelectedIndex = 0;
        }
        private void gridView_thuoc_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle < 0) e.Info.DisplayText = "";
                else e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
            else { e.Info.DisplayText = "STT"; }
            e.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
        }

        private void rpcboPhuongThuc_Enter(object sender, EventArgs e)
        {
            LookUpEdit lookcbo = sender as LookUpEdit;
            lookcbo.EditValue = Convert.ToInt16(1);
        }

        private void rpcboDonViDung_Enter(object sender, EventArgs e)
        {
            if (gridView_thuoc.GetRowCellValue(gridView_thuoc.FocusedRowHandle, gridColumnDVT)!= null)
            {
                string p = gridView_thuoc.GetRowCellValue(gridView_thuoc.FocusedRowHandle, gridColumnDVT).ToString();
                DataTable _dvDVD = LayDSDVD_Theodonvi(p);
                string tam = "";
                if (_dvDVD.Rows.Count > 0)
                    tam = _dvDVD.Rows[0]["Donvisudung"].ToString();
                LookUpEdit lok = sender as LookUpEdit;
                lok.EditValue = tam;
            } 
        }

        private void rpcboTGDung_Enter(object sender, EventArgs e)
        {
            LookUpEdit lookcbo = sender as LookUpEdit;
            lookcbo.EditValue = "2";
        }

        private void rpcboBuoiDung_Enter(object sender, EventArgs e)
        {
            LookUpEdit lookcbo = sender as LookUpEdit;
            lookcbo.EditValue = "SÁNG - TRƯA - TỐI";
        }

        private void gridView_thuoc_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int currentCol = e.Column.VisibleIndex;
            DataRow dr = gridView_thuoc.GetDataRow(gridView_thuoc.FocusedRowHandle);
            if (currentCol == gridView_thuoc.Columns["bdid"].VisibleIndex)
                machung =Uit.it_Parse.ToInteger(dr["bdid"]);
            if (machung > 0)
            {
                DataRow drmoi = dtThuoc.NewRow(); ;
                foreach (DataRow drd in dtThuoc.Rows)
                {
                    if (int.Parse(drd["bdid"].ToString()) == machung)
                        drmoi = drd;
                }
                m_gridView_CellValueChanged(gridView_thuoc, drmoi, e);
                if (txtsophieu.Text == "" && cbo_noigiaothuoc.EditValue != null)
                {
                    txtsophieu.Text = dv_khac.SobnToaThuocNT(cbo_noigiaothuoc.EditValue.ToString(), frmLogin.nd.MaDonVi).ToString();
                }
            }
        }
        private void btnXoaDong_Click(object sender, EventArgs e)
        {
            gridView_thuoc.DeleteSelectedRows();
            DataRow dr = gridView_thuoc.GetDataRow(gridView_thuoc.FocusedRowHandle);
        
        }
        public DataTable LayDSDVD_Theodonvi(string DVT)
        {
            DataTable dttmp = new DataTable();
            dttmp.Columns.Add("Donvisudung");

            DataTable dt = new DataTable();
            dt.Columns.Add("Donvisudung");

            for (int i = 0; i < _dvd.Rows.Count; i++)
            {
                if (DVT != "")
                {
                    if (_dvd.Rows[i]["donvitoathuoc"].ToString().ToUpper() == DVT.Trim().ToUpper())
                    {
                        dt.Rows.Add(_dvd.Rows[i]["donvisudung"].ToString().ToUpper());
                        dttmp.Rows.Add(_dvd.Rows[i]["donvisudung"].ToString().ToUpper());
                    }
                }
                else
                {
                    dt.Rows.Add(_dvd.Rows[i]["donvisudung"].ToString().ToUpper());
                    dttmp.Rows.Add(_dvd.Rows[i]["donvisudung"].ToString().ToUpper());
                }
            }

            if (dttmp.Rows.Count > 0)
            {
                for (int i = 0; i < _dvd.Rows.Count; i++)
                {
                    for (int j = 0; j < dttmp.Rows.Count; j++)
                    {
                        if (_dvd.Rows[i]["donvisudung"].ToString().ToUpper() != dttmp.Rows[j]["donvisudung"].ToString().ToUpper())
                            dt.Rows.Add(_dvd.Rows[i]["donvisudung"].ToString().ToUpper());
                    }
                }
            }

            return dt;
        }
        private void rpscbo_thuoc_Validating(object sender, CancelEventArgs e)
        {
            SearchLookUpEdit look = sender as SearchLookUpEdit;
            if (look.Text != "")
            {
                for (int row = 0; row < gridView_thuoc.RowCount - 1; row++)
                {
                    if (look.EditValue.ToString().Equals(gridView_thuoc.GetRowCellValue(row, gridColumn_bdid).ToString()))
                    {
                        XtraMessageBox.Show("Thuốc này đã tồn tại ", "Thông Báo");
                        e.Cancel = true;
                        return;
                    }
                }
            }
        }
        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (IsValidToa())
            {
                LuuToaThuoc();
            }
        }
        bool IsValidToa()
        {
            int idThuoc;
            bool KhongChoTao = false;
            string sThuocKhongDu = ""; //MaToa = "", sThuocSaiTen = "", sThuocNgung = ""
            if (cbo_noigiaothuoc.EditValue == null)
            {
                XtraMessageBox.Show("Chưa chọn nơi giao thuốc","Thông Báo");
                return false;
            }
            // benh nhan da xuat vien
            if (tntmstctl.m_KiemTraXuatVien(bninfo.SoNhapVien) == null)
            {
                //XtraMessageBox.Show("Bệnh Nhân đã xuất viện", "Thông Báo");
               // return false;
            }
            if (txtsonhapvien.Text == "")
            {
                XtraMessageBox.Show("Chưa chọn bệnh nhân");
                return false;
            }
            //Kiem tra con bsi cghi dinh 
            if (scboBS.EditValue == null || txtChuanDoan.Text=="")
            {
                XtraMessageBox.Show("Chưa chọn Bác Sĩ hoặc Chuẩn đoán", "Thông Báo");
                return false;
            }

            //quyen sua toa thuoc
            //if (TOA_ChiBoSung)
            //{
            //    MessageBox.Show("Khong sua duoc Toa qua ngay/ Toa cua bac si khac!");
            //    return false;
            //}
            //string ThongBao;
            //if (LaNgayNghi(out ThongBao))
            //{
            //    MessageBox.Show(ThongBao);
            //    return false;
            //}
            DataView dvThuoc = new DataView(tntmstctl.m_soluongtonkhonoitru(cbo_noigiaothuoc.EditValue.ToString()));//slton,ksslgx
            DataView dvThuoc_Kholtmp = new DataView(tntmstctl.m_kholtmp_toapk());//slg
           
            for (int row = 0; row < gridView_thuoc.RowCount-1; row++)
            {

                if (gridView_thuoc.GetRowCellValue(row, gridColumn_bdid) != null && gridView_thuoc.GetRowCellValue(row,gridColumn_sl) != null)
                {
                    dvThuoc.Sort = "bdid"; dvThuoc_Kholtmp.Sort = "bdid";
                    int SLTon, slksslgx,solgtam;
                    idThuoc = dvThuoc.Find(Convert.ToInt16(gridView_thuoc.GetRowCellValue(row, gridColumn_bdid).ToString()));
                    if (idThuoc == -1)
                    {
                        SLTon = 0;
                        slksslgx = 0;
                    }
                    else
                    {
                        SLTon = Uit.it_Parse.ToInt16(dvThuoc[idThuoc]["slton"]);
                        slksslgx = Uit.it_Parse.ToInt16(dvThuoc[idThuoc]["slgdat"]);
                    }
                    int idthuoc_ = dvThuoc_Kholtmp.Find(Convert.ToInt16(gridView_thuoc.GetRowCellValue(row, gridColumn_bdid).ToString()));
                    if (idThuoc == -1)
                        solgtam = 0;
                    else
                        solgtam = Uit.it_Parse.ToInt16(dvThuoc_Kholtmp[idthuoc_]["slg"]);
                    if (solgtam < 0)
                        solgtam = 0;
                    SLTon = SLTon - slksslgx - solgtam;
                    int SLKe = Uit.it_Parse.ToInteger(gridView_thuoc.GetRowCellValue(row, gridColumn_sl));
                    if (SLKe > SLTon)
                    { 
                        DataView dvThuoc_ = dtThuoc.DefaultView;
                        ColumnView vieww = gridView_thuoc.Columns[row].View;
                        dvThuoc_.Sort = "bdid"; 
                        DevExpress.XtraGrid.StyleFormatCondition cn;
                        cn = new DevExpress.XtraGrid.StyleFormatCondition(FormatConditionEnum.GreaterOrEqual, vieww.Columns["slg"], null, SLTon);
                        cn.Appearance.BackColor = Color.Red;
                        gridView_thuoc.FormatConditions.Add(cn);
                        gridView_thuoc.BestFitColumns();
                       // gridView_thuoc.Appearance.SelectedRow.BackColor = Color.Yellow;
                        sThuocKhongDu = sThuocKhongDu + dvThuoc_[dvThuoc_.Find(Convert.ToInt16(gridView_thuoc.GetRowCellValue(row, gridColumn_bdid).ToString()))]["tenbd"].ToString() + " kê: " + SLKe + ". Tồn " + SLTon.ToString().TrimEnd() + " \n ";
                        KhongChoTao = true;
                    }
                   
                }
            }
            if (KhongChoTao)
            {
                XtraMessageBox.Show( "        Màu đỏ: thuốc không đủ số lượng \n " + sThuocKhongDu ,"Thông Báo");
                return false;
            }
            return true;
        }
        void LuuToaThuoc()
        {
            float tongtien=0;
            string _sqltntmst="",_sqltnt="";
            ThuocNoiTruMstDTO tntmstdto = new ThuocNoiTruMstDTO();
            ThuocNoiTruCTL tntctl = new ThuocNoiTruCTL();
            if (!bninfo.Coratoa)
                txtsophieu.Text= dv_khac.SobnToaThuocNT(cbo_noigiaothuoc.EditValue.ToString(), frmLogin.nd.MaDonVi).ToString();
            tntmstdto.Sobn = txtsophieu.Text;
            tntmstdto.Ngay = Uit.it_Date.CurrentDate("yyyy-MM-dd");
            tntmstdto.Makho1 = cbo_noigiaothuoc.EditValue.ToString();
            tntmstdto.Madvpk = frmLogin.nd.MaDonVi;
            tntmstdto.Chandoan =Uit.it_Font.UnicodeToVNI(txtChuanDoan.Text);
            tntmstdto.ChandoanUni = txtChuanDoan.Text;
            tntmstdto.Idnguoinhap = frmLogin.nd.IDNguoiDung;
            tntmstdto.Yymm = Uit.it_Date.CurrentDate("yy") + Uit.it_Date.CurrentDate("MM");
            tntmstdto.SoHS1= bninfo.MaSo;
            tntmstdto.SoNhapvien1 = txtsonhapvien.Text;
            tntmstdto.Tungay= dt_TuNgay.DateTime.ToString("yyyy-MM-dd");
            tntmstdto.Denngay = dtDenNgay.DateTime.ToString("yyyy-MM-dd");
            tntmstdto.HA1 = txtHA.Text;
            tntmstdto.Mach1 =  Uit.it_Parse.ToInteger(txtmm.Text);
            tntmstdto.Ghichu= Uit.it_Font.UnicodeToVNI(txtGhiChuSD.Text);
            tntmstdto.GhiChuUni1 = txtGhiChuSD.Text;
            tntmstdto.NhietDo1 =  Uit.it_Parse.ToInteger(txtNhietDo.Text);
            tntmstdto.Thetrang = Uit.it_Font.UnicodeToVNI(memoEdit_DB.Text);
            tntmstdto.TheTrangUni1 = memoEdit_DB.Text;
            tntmstdto.Idbacsi = Uit.it_Parse.ToInteger(scboBS.EditValue);
            if (radioGroup1.SelectedIndex == 1)
                tntmstdto.Doituong = 2;
            else
                tntmstdto.Doituong = 4;
            for (int i = 0; i < gridView_thuoc.RowCount - 1; i++)
            {
                DataRow dr = gridView_thuoc.GetDataRow(i);
                ThuocNoiTruDTO tntdto = new ThuocNoiTruDTO();
                tntdto.Sobn = txtsophieu.Text;
                tntdto.Stt = i + 1;
                tntdto.Bdid = Uit.it_Parse.ToInteger(dr["bdid"]);
                tntdto.Dvt = Uit.it_Font.UnicodeToVNI(dr["dvt"].ToString());
                tntdto.Slg = Uit.it_Parse.ToInteger(dr["slg"]);
                tntdto.Slgcosan = float.Parse(dr["slgcosan"].ToString() == "" ? "0" : dr["slgcosan"].ToString());
                tntdto.Dongia = Uit.it_Parse.ToInteger(dr["dongia"]);
                tntdto.Trigia = (float.Parse(tntdto.Slg.ToString()) + tntdto.Slgcosan) * float.Parse(tntdto.Dongia.ToString());
                tntdto.Langay = Uit.it_Parse.ToInteger(dr["langay"]);
                tntdto.Slglan = float.Parse(dr["slglan"].ToString() == "" ? "0" : dr["slglan"].ToString());
                tntdto.Slgsd = float.Parse(dr["Slgsd"].ToString() == "" ? "0" : dr["Slgsd"].ToString());
                tntdto.Usageid = Uit.it_Parse.ToInteger(dr["usageid"]);
                tntdto.Dvsudung = Uit.it_Font.UnicodeToVNI(dr["dvsudung"].ToString());
                tntdto.Tgdung = Uit.it_Font.UnicodeToVNI(dr["tgdung"].ToString() == "1" ? "Trước ăn" : "Sau ăn");
                tntdto.Buoidung = Uit.it_Font.UnicodeToVNI(dr["buoidung"].ToString());
                tntdto.Donvitinh = dr["dvt"].ToString();
                tntdto.DvSuDungUni1 = dr["dvsudung"].ToString();
                tntdto.TgDungUni1 = dr["tgdung"].ToString() == "1" ? "Trước ăn" : "Sau ăn";
                tntdto.BuoiDungUni1 = dr["buoidung"].ToString();
                tntdto.Giabhyt = Uit.it_Parse.ToInteger(dr["giabhyt"]);
                tongtien = tongtien + tntdto.Trigia;
                if (tntdto.Slgsd > 0)
                {
                    _sqltnt = _sqltnt + " " + tntctl.m_Insert_(tntdto.Sobn, tntdto.Stt, tntdto.Bdid, tntdto.Dvt, tntdto.Slg, tntdto.Slgcosan,
                        tntdto.Dongia, tntdto.Trigia, tntdto.Langay, tntdto.Slglan, tntdto.Usageid, 0, 0, tntdto.Slgsd, tntdto.Dvsudung, tntdto.Tgdung, tntdto.Buoidung, tntdto.Donvitinh,
                       tntdto.DvSuDungUni1, tntdto.TgDungUni1, tntdto.BuoiDungUni1, tntdto.Giabhyt);
                    _sqltnt = _sqltnt + " " + dv_khac.Insert_kholetmp_toapk(tntdto.Bdid, tntdto.Slgsd);
                }

            }
            if (gridView_thuoc.RowCount == 1 || tongtien==0)
            {
                bninfo.Coratoa = false;
                XtraMessageBox.Show("Lưu toa thất bại");
                return;
            }
            //neu khong update thi no insert
            FeentMstCTL feentmst = new FeentMstCTL();
            tntmstdto.Sotien = Uit.it_Parse.ToInteger(tongtien);
            if (bninfo.Coratoa)
            {
                _sqltntmst = tntmstctl.m_Update_(tntmstdto.Sobn, tntmstdto.Ngay, tntmstdto.Makho1, tntmstdto.Sotien,
            tntmstdto.Madvpk, tntmstdto.Chandoan, tntmstdto.Idnguoinhap, tntmstdto.Yymm, tntmstdto.SoHS1, tntmstdto.SoNhapvien1, 0, tntmstdto.Tungay, tntmstdto.Denngay,
            tntmstdto.HA1, tntmstdto.Mach1, tntmstdto.Ghichu, tntmstdto.NhietDo1, tntmstdto.Thetrang, tntmstdto.Idbacsi, tntmstdto.GhiChuUni1, tntmstdto.TheTrangUni1, tntmstdto.ChandoanUni,tntmstdto.Doituong);
                _sqltntmst = _sqltntmst + " " + tntctl.m_Delete_(tntmstdto.Sobn);
                 _sqltntmst = _sqltntmst + " "+ feentmst.m_Update_(tntmstdto.Sobn, tntmstdto.Ngay, tntmstdto.SoHS1, tntmstdto.Sotien, tntmstdto.GhiChuUni1, tntmstdto.Idbacsi, tntmstdto.Madvpk, tntmstdto.ChandoanUni,
                    5, tntmstdto.Ghichu, tntmstdto.Chandoan, tntmstdto.Idnguoinhap, tntmstdto.SoNhapvien1);

            }
            else
            {
                _sqltntmst = tntmstctl.m_Insert_(tntmstdto.Sobn, tntmstdto.Ngay, tntmstdto.Makho1, tntmstdto.Sotien,
                    tntmstdto.Madvpk, tntmstdto.Chandoan, tntmstdto.Idnguoinhap, tntmstdto.Yymm, tntmstdto.SoHS1, tntmstdto.SoNhapvien1, 0, tntmstdto.Tungay, tntmstdto.Denngay,
                    tntmstdto.HA1, tntmstdto.Mach1, tntmstdto.Ghichu, tntmstdto.NhietDo1, tntmstdto.Thetrang, tntmstdto.Idbacsi, tntmstdto.GhiChuUni1, tntmstdto.TheTrangUni1, tntmstdto.ChandoanUni,tntmstdto.Doituong);
                _sqltntmst =_sqltntmst+" "+ feentmst.m_Insert_(tntmstdto.Sobn, tntmstdto.Ngay, tntmstdto.SoHS1, tntmstdto.Sotien, tntmstdto.GhiChuUni1, tntmstdto.Idbacsi, tntmstdto.Madvpk, tntmstdto.ChandoanUni,
                   5, tntmstdto.Ghichu, tntmstdto.Chandoan, tntmstdto.Idnguoinhap, tntmstdto.SoNhapvien1);
            }

            string _sqlkq = _sqltntmst + " " + _sqltnt ;
            if (Uit.it_SQL.ExecuteNonQuery(_sqlkq))
            {
                bninfo.Coratoa = true;
                gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
                XtraMessageBox.Show("Lưu thành công");
            }
            else
            {
                bninfo.Coratoa = false;
                XtraMessageBox.Show("Lưu toa thất bại");
            }
        }
        // tap danh sach toa thuoc
        void LoadDSPhieu()
        {
            dtDenNgay_DS.EditValue = Uit.it_Date.CurrentDate2();
            dtTuNgay_DS.Properties.MaxValue = Uit.it_Date.CurrentDate2();
            DateTime dtmin = new DateTime(dtDenNgay_DS.DateTime.Year, dtDenNgay_DS.DateTime.Month-1, 1);
            dtTuNgay_DS.Properties.MinValue = dtmin;
            dtTuNgay_DS.EditValue = Uit.it_Date.CurrentDate2();
            dtDenNgay_DS.Properties.MinValue = dtmin;
        }
        string sTenSearch = "";
        string sColSearch ;
        private void OpenTap(string NameTap)
        {
            for (int i = 0; i < xtraTabControl1.TabPages.Count; i++)
            {
                if (xtraTabControl1.TabPages[i].Name.Equals(NameTap))
                {
                    xtraTabControl1.TabPages[i].PageEnabled = true;
                    // xtraTabControlChiPhiNGTru.TabPages[i].Focus();
                }
                else
                    xtraTabControl1.TabPages[i].PageEnabled = false;
            }
        }
        DataTable dttk = new DataTable();
        private void gridView_DS_ColumnFilterChanged(object sender, EventArgs e)
        {
            ColumnView view = sender as ColumnView;
            view.ActiveFilter.Add(view.Columns[sColSearch], new ColumnFilterInfo("[" + sColSearch + "] Like '%" + sTenSearch + "%'", ""));

        }
        private void gridView_DS_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            sTenSearch = e.Value.ToString();
            sColSearch = e.Column.FieldName;
        }
        private void btnTimKiem_DS_Click(object sender, EventArgs e)
        {
            dttk = dv_khac.DanhSachToaThuoc(dtTuNgay_DS.DateTime.ToString("MM/dd/yyyy"), dtDenNgay_DS.DateTime.ToString("MM/dd/yyyy"), frmLogin.nd.MaDonVi);
            gridControl1.DataSource = dttk;

        }

        private void gridView_DS_DoubleClick(object sender, EventArgs e)
        {
            DataRow dr = gridView_DS.GetDataRow(gridView_DS.FocusedRowHandle);
            if (dr == null) return;
            DataView dtvtk = dttk.DefaultView;
            dtvtk.Sort = "sobn";
            bninfo.Coratoa = true;
            int id_dt = dtvtk.Find(gridView_DS.GetRowCellValue(gridView_DS.FocusedRowHandle, gridColumn_sobn).ToString());
            bninfo.Ten=dtvtk[id_dt]["tenbn"].ToString();
            bninfo.Gioi = dtvtk[id_dt]["GioiTinh"].ToString();
            bninfo.NamSinh = Uit.it_Parse.ToInteger(dtvtk[id_dt]["NamSinh"]);
            bninfo.Tuoi = Uit.it_Parse.ToInteger(dtvtk[id_dt]["tuoi"]);
			bninfo.DiaChi = dtvtk[id_dt]["DiaChi"].ToString();
            txtsophieu.Text= dtvtk[id_dt]["sobn"].ToString();
            txthoten.Text = bninfo.Ten;
            txtGioiTinh.Text =bninfo.Gioi;
            txtsonhapvien.Text = dtvtk[id_dt]["sonhapvien"].ToString();
            txttuoi.Text = bninfo.Tuoi.ToString();
            txtDiaChi.Text = bninfo.DiaChi;
            txtngaylanh.Text =Uit.it_Parse.ToDateTime(dtvtk[id_dt]["ngay"],"dd/MM/yyyy").ToString();
            cbo_noigiaothuoc.EditValue = dtvtk[id_dt]["makho"];
            txtChuanDoan.Text = dtvtk[id_dt]["chandoan"].ToString();
            dtDenNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["denngay"]);
            dt_TuNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["tungay"]);
            scboBS.EditValue= dtvtk[id_dt]["idbacsi"];
            txtGhiChuSD.Text =  dtvtk[id_dt]["GhiChuUni"].ToString();
            memoEdit_DB.Text = dtvtk[id_dt]["TheTrangUni"].ToString();
            txtNhietDo.Text = dtvtk[id_dt]["NhietDo"].ToString();
            txtmm.Text =dtvtk[id_dt]["Mach"].ToString();
            txtHA.Text = dtvtk[id_dt]["Ha"].ToString();
            txtthang.Text = dtvtk[id_dt]["yymm"].ToString().Substring(2, 2) + "-" + dtvtk[id_dt]["yymm"].ToString().Substring(0, 2);
            //t.xacnhan,,,t.sohs,t.sotien,t.,t.madvpk,t.idnguoinhap,t.toaxv
            bninfo.MaSo = dtvtk[id_dt]["sohs"].ToString();
            gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
            DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(dtvtk[id_dt]["sohs"].ToString());
            bool brealo = true;
            if(Uit.it_Parse.ToBoolean(dtvtk[id_dt]["process"])== true)
                 brealo=false;
            bninfo.Madonvi = dtkt.Rows[0]["traibenh"].ToString();
            bninfo.Tendonvi = dtkt.Rows[0]["tendonvi"].ToString();
            if (dtkt.Rows[0]["traibenh"].ToString() != dtvtk[id_dt]["madvpk"].ToString())
                brealo = false;
            //if(dtkt.Rows[0]["xuatvien"].ToString() !="")
            //    brealo = false;
            if (Uit.it_Parse.ToInteger(dtvtk[id_dt]["doituong"]) == 2) 
                radioGroup1.SelectedIndex = 1;
            else
                radioGroup1.SelectedIndex = 0;
            if (brealo == false)
                gridView_thuoc.OptionsBehavior.ReadOnly = true;
            else
                gridView_thuoc.OptionsBehavior.ReadOnly = false;
            OpenTap(xtraTabPage1.Name);
                
        }
       
        private void gridView_DS_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                DataRow dr = gridView_DS.GetDataRow(gridView_DS.FocusedRowHandle);
                if (dr == null) return;
                DataView dtvtk = dttk.DefaultView;
                dtvtk.Sort = "sobn";
                bninfo.Coratoa = true;
                int id_dt = dtvtk.Find(gridView_DS.GetRowCellValue(gridView_DS.FocusedRowHandle, gridColumn_sobn).ToString());
                bninfo.Ten = dtvtk[id_dt]["tenbn"].ToString();
                bninfo.Gioi = dtvtk[id_dt]["GioiTinh"].ToString();
                bninfo.NamSinh = Uit.it_Parse.ToInteger(dtvtk[id_dt]["NamSinh"]);
                bninfo.Tuoi = Uit.it_Parse.ToInteger(dtvtk[id_dt]["tuoi"]);
                bninfo.DiaChi = dtvtk[id_dt]["DiaChi"].ToString();
                txtsophieu.Text = dtvtk[id_dt]["sobn"].ToString();
                txthoten.Text = bninfo.Ten;
                txtGioiTinh.Text = bninfo.Gioi;
                txtsonhapvien.Text = dtvtk[id_dt]["sonhapvien"].ToString();
                txttuoi.Text = bninfo.Tuoi.ToString();
                txtDiaChi.Text = bninfo.DiaChi;
                txtngaylanh.Text = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["ngay"], "dd/MM/yyyy").ToString();
                cbo_noigiaothuoc.EditValue = dtvtk[id_dt]["makho"];
                txtChuanDoan.Text = dtvtk[id_dt]["chandoan"].ToString();
                dtDenNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["denngay"]);
                dt_TuNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["tungay"]);
                scboBS.EditValue = dtvtk[id_dt]["idbacsi"];
                txtGhiChuSD.Text = dtvtk[id_dt]["GhiChuUni"].ToString();
                memoEdit_DB.Text = dtvtk[id_dt]["TheTrangUni"].ToString();
                txtNhietDo.Text = dtvtk[id_dt]["NhietDo"].ToString();
                txtmm.Text = dtvtk[id_dt]["Mach"].ToString();
                txtHA.Text = dtvtk[id_dt]["Ha"].ToString();
                txtthang.Text = dtvtk[id_dt]["yymm"].ToString().Substring(2, 2) + "-" + dtvtk[id_dt]["yymm"].ToString().Substring(0, 2);
                //t.xacnhan,,,t.sohs,t.sotien,t.,t.madvpk,t.idnguoinhap,t.toaxv
                bninfo.MaSo = dtvtk[id_dt]["sohs"].ToString();
                gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
                DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(dtvtk[id_dt]["sohs"].ToString());
                bool brealo = true;
                if (Uit.it_Parse.ToBoolean(dtvtk[id_dt]["process"]) == true)
                    brealo = false;
                if (dtkt.Rows[0]["traibenh"].ToString() != dtvtk[id_dt]["madvpk"].ToString())
                    brealo = false;
                //if (dtkt.Rows[0]["xuatvien"].ToString() != "")
                //    brealo = false;
                if (Uit.it_Parse.ToInteger(dtvtk[id_dt]["doituong"])==2)
                    radioGroup1.SelectedIndex = 1;
                else
                    radioGroup1.SelectedIndex = 0;
                if (brealo == false)
                    gridView_thuoc.OptionsBehavior.ReadOnly = true;
                else
                    gridView_thuoc.OptionsBehavior.ReadOnly = false;
                OpenTap(xtraTabPage1.Name);
            }
        }

        private void btnXoaPhieu_Click(object sender, EventArgs e)
        {
            FeentMstCTL feentmst = new FeentMstCTL();
            string sobnx = gridView_DS.GetFocusedRowCellValue("sobn").ToString();
            if (XtraMessageBox.Show("Bạn có muốn xóa số phiếu" + sobnx + " ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                string _sqldelete = tntmstctl.m_Delete_(sobnx) + feentmst.m_Delete_(sobnx);
                if (Uit.it_SQL.ExecuteNonQuery(_sqldelete))
                {
                    XtraMessageBox.Show("Xóa thành công");
                    gridView_DS.DeleteSelectedRows();
                }
            }
              
        }

        private void btndsphieu_Click(object sender, EventArgs e)
        {
            OpenTap(xtraTabPage2.Name);
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDocLai_Click(object sender, EventArgs e)
        {
            dttk = dv_khac.DanhSachToaThuoc(dtTuNgay_DS.DateTime.ToString("MM/dd/yyyy"), dtDenNgay_DS.DateTime.ToString("MM/dd/yyyy"), frmLogin.nd.MaDonVi);
            gridControl1.DataSource = dttk;
        }

        private void btnToaThuocMoi_Click(object sender, EventArgs e)
        {
            OpenTap(xtraTabPage1.Name);
            DatatableKhoitao();

        }
        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            if (txtsonhapvien.Text != "" && txtsophieu.Text != "")
            {
               if (Uit.it_Parse.ToBoolean(dv_khac.kiemtrachuyenkhole(txtsophieu.Text)))
                {
                    XtraMessageBox.Show("Thuốc đã được chuyển xuống dược", "Thông báo");
                    return;
                }

                if (dv_khac.Chuyenkholeduoc(txtsonhapvien.Text, txtsophieu.Text))
                    XtraMessageBox.Show("Chuyển thành công", "Thông báo");
                else
                    XtraMessageBox.Show("Chuyển thất bại", "Thông báo");
            }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void bntInBangKeThuoc_Click(object sender, EventArgs e)
        {
            rpt_BangKeThuoc rpt = new rpt_BangKeThuoc();
            DataRow dr = gridView_DS.GetDataRow(gridView_DS.FocusedRowHandle);
            if (dr == null) return;
            DataView dtvtk = dttk.DefaultView;
            dtvtk.Sort = "sobn";
            int id_dt = dtvtk.Find(gridView_DS.GetRowCellValue(gridView_DS.FocusedRowHandle, gridColumn_sobn).ToString());
            rpt.tenbn = dtvtk[id_dt]["tenbn"].ToString();
            rpt.sonv = dtvtk[id_dt]["sonhapvien"].ToString();
            rpt.sohs = dtvtk[id_dt]["sohs"].ToString();
            //dtDenNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["denngay"]);
            //dt_TuNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["tungay"]);
            //scboBS.EditValue = dtvtk[id_dt]["idbacsi"];
            DataTable dtbk = dv_khac.BangKeThuoc(frmLogin.nd.MaDonVi, rpt.sonv);
            int i = 0;
            foreach (DataRow dro in dtbk.Rows)
            {
                DataRow drr = rpt.ds.PhieuPhatThuoc.NewPhieuPhatThuocRow();
                drr["stt"]=i+1;
                drr["tenbd"] = " "+ dro["tenbd"].ToString();
                drr["slgsd"] = dro["slgsd"];
                drr["dvt"] = dro["dvt"];
                drr["thanhtien"] = dro["thanhtien"];
                drr["cachdung"] = "  "+dro["cachdung"].ToString() + "    " + frmLogin.nd.MaDonVi;
                i = i + 1;
                rpt.ds.PhieuPhatThuoc.Rows.Add(drr);

            }
            DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(dtvtk[id_dt]["sohs"].ToString());
            rpt.tendonvi = dtkt.Rows[0]["tendonvi"].ToString();
            rpt.ShowPreview();

        }

        private void btnInPhieu_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView_thuoc.GetDataRow(0);
            if (dr == null) return;
            rpt_PhieuPhatThuoc rpt = new rpt_PhieuPhatThuoc();    
            rpt.tenbn = txthoten.Text;
            rpt.sonv = txtsonhapvien.Text;
            rpt.sophieu = txtsophieu.Text;
            rpt.denngay = dtDenNgay.DateTime.ToString("dd/MM/yyyy");
            rpt.tungay = dt_TuNgay.DateTime.ToString("dd/MM/yyyy");
            rpt.gioitinh = txtGioiTinh.Text;
            int tuoi = Uit.it_Parse.ToInteger(txttuoi.Text);
            if (tuoi > 0)
                rpt.tuoi = tuoi.ToString();
            else
                rpt.tuoi = "";
            rpt.diachi= txtDiaChi.Text;
            if (radioGroup1.SelectedIndex == 0)
                rpt.doituong = "Bệnh nhân";
            else
                rpt.doituong = "BHYT";
            DataTable dtbk = dv_khac.PhieuPhatThuoc(dr["sobn"].ToString());
            int i = 0;
            foreach (DataRow dro in dtbk.Rows)
            {
                DataRow drr = rpt.ds.PhieuPhatThuoc.NewPhieuPhatThuocRow();
                drr["stt"] = i + 1;
                drr["tenbd"] = " " + dro["tenbd"].ToString();
                drr["slgsd"] = dro["slgsd"];
                drr["dvt"] = dro["dvt"];
                drr["dongia"] = dro["dongia"];
                drr["thanhtien"] = dro["thanhtien"];
                drr["cachdung"] = "  " + dro["cachdung"].ToString();
                i = i + 1;
                rpt.ds.PhieuPhatThuoc.Rows.Add(drr);

            }
            DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(bninfo.MaSo);
            rpt.tendonvi = dtkt.Rows[0]["tendonvi"].ToString();
            rpt.bschid = scboBS.Text;
            rpt.ShowPreview();

        }
       

       
    }
}